<?php
namespace app\api\service;
use app\api\model\Member;
use app\common\service\CommonService;
class MemberService extends CommonService
{
    const ACCOUNT_PASSWORD_NOT_MATCH =1; //账号密码不匹配
    const ACCOUNT_FROZEN = 2;//账号被冻结
    const ACCOUNT_PASSWORD_MATCH = 0; //账号密码匹配
    const MESSAGE =[
        self::ACCOUNT_PASSWORD_MATCH=>"登录成功",
        self::ACCOUNT_PASSWORD_NOT_MATCH=>"账号密码不匹配",
        self::ACCOUNT_FROZEN=>"账号被冻结"
    ];
    public function initialize()
    {
        $this->model = new Member();
    }

    public function register($email,$password,$pid=0)
    {
          $model = $this->model;
          $tree = "";
          if (!empty($pid)) {
              $member = $model->find($pid);
              if (!$member->isEmpty()) {
                  $tree = rtrim($member->tree,"/").DIRECTORY_SEPARATOR.$pid;
              }
          }
          $model->pid = $pid;
          $model->email = $email;
          $model->password= $password;
          $model->register_ip = request()->ip();
          $model->tree = $tree;
          $model->save();
          return $model->id;
    }

    public function login($email,$password)
    {
        $member = $this->getOne(["email"=>$email]);
        if ($member->isEmpty()) {
            return self::ACCOUNT_PASSWORD_NOT_MATCH;
        } elseif ($member->status==self::DENY_STATUS) {
            return self::ACCOUNT_FROZEN;
        } elseif (!password_verify($password,$member->password)) {
            return self::ACCOUNT_PASSWORD_NOT_MATCH;
        } else {
            $member->login_ip=request()->ip();
            $member->login_at = date("Y-m-d H:i:s");
            $member->save();
            return self::ACCOUNT_PASSWORD_MATCH;
        }
    }

}